<?php
declare(strict_types=1);

/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\Admin\Service\System;

use App\Admin\Mapper\System\SystemUserMapper;
use App\Admin\Model\System\SystemUser;
use App\Admin\Service\Setting\SettingConfigService;
use DI\Attribute\Inject;
use DI\DependencyException;
use DI\NotFoundException;
use Newbie\Cache\Redis;
use Newbie\Event\UserLoginAfter;
use Newbie\Event\UserLoginBefore;
use Newbie\Event\UserLogout;
use Newbie\exception\CaptchaException;
use Newbie\exception\NormalStatusException;
use Newbie\exception\UserBanException;
use Newbie\helper\NewbieCode;
use Newbie\Interfaces\UserServiceInterface;
use Newbie\Vo\UserServiceVo;
use Psr\SimpleCache\InvalidArgumentException;
use Webman\Event\Event;


/**
 * 用户登录
 */
class UserAuthService implements UserServiceInterface {

    #[Inject]
    protected SystemUserMapper $mapper;

    /**
     * 检查用户提交的验证码
     * @param String $code
     * @param $key
     * @return bool
     * @throws DependencyException
     * @throws NotFoundException
     */
    public function checkCaptcha (string $code, $key): bool {
        if (!\redis()->get('captcha:' . $key)) {
            return false;
        }
        return \Tinywan\Captcha\Captcha::check($code, $key);
    }

    /**
     * 登录
     * @param UserServiceVo $userServiceVo
     * @return string
     * @throws DependencyException
     * @throws NotFoundException
     * @throws InvalidArgumentException
     */
    public function login (UserServiceVo $userServiceVo): string {
        $mapper = $this->mapper;
        try {
            Event::emit('SystemUserLoginBefore', new UserLoginBefore(['username' => $userServiceVo->getUsername(), 'password' => $userServiceVo->getPassword()]));
            $userinfo = $mapper->checkUserByUsername($userServiceVo->getUsername())->toArray();
            $password = $userinfo['password'];
            unset($userinfo['password']);
            $userLoginAfter = new UserLoginAfter($userinfo);
            $webLoginVerify = container()->get(SettingConfigService::class)->getConfigByKey('web_login_verify');
            if (isset($webLoginVerify['value']) && $webLoginVerify['value'] === '1') {
                if (!$this->checkCaptcha($userServiceVo->getVerifyCode(), $userServiceVo->getVerifyKey())) {
                    $userLoginAfter->message     = \t('jwt.code_error');
                    $userLoginAfter->loginStatus = false;
                    Event::emit('SystemUserLoginAfter', $userLoginAfter);
                    throw new CaptchaException;
                }
            }
            if ($mapper->checkPass($userServiceVo->getPassword(), $password)) {
                if (
                    ($userinfo['status'] == SystemUser::USER_NORMAL)
                    ||
                    ($userinfo['status'] == SystemUser::USER_BAN && $userinfo['id'] == env('SUPER_ADMIN'))
                ) {
                    $userLoginAfter->message = \t('jwt.login_success');
                    $token                   = \user()->getToken($userLoginAfter->userinfo);
                    $userLoginAfter->token   = $token;
                    Event::emit('SystemUserLoginAfter', $userLoginAfter);
                    return $token;
                } else {
                    $userLoginAfter->loginStatus = false;
                    $userLoginAfter->message     = \t('jwt.user_ban');
                    Event::emit('SystemUserLoginAfter', $userLoginAfter);
                    throw new UserBanException;
                }
            } else {
                $userLoginAfter->loginStatus = false;
                $userLoginAfter->message     = \t('jwt.password_error');
                Event::emit('SystemUserLoginAfter', $userLoginAfter);
                throw new NormalStatusException;
            }
        } catch (\Exception $e) {
            if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
                throw new NormalStatusException(\t('jwt.username_error'), NewbieCode::NO_DATA);
            }
            if ($e instanceof NormalStatusException) {
                throw new NormalStatusException(\t('jwt.password_error'), NewbieCode::PASSWORD_ERROR);
            }
            if ($e instanceof UserBanException) {
                throw new NormalStatusException(\t('jwt.user_ban'), NewbieCode::USER_BAN);
            }
            if ($e instanceof CaptchaException) {
                throw new NormalStatusException(\t('jwt.code_error'));
            }
            throw $e;
            //throw new NormalStatusException(\t('jwt.unknown_error'));
        }
    }

    /**
     * 用户退出
     */
    public function logout (): void {
        $user = user();
        container()->get(SystemUserService::class)->clearCache($user->getId());
        $redis = container()->get(Redis::class);
        $key   = sprintf("Token:%s", $user->getId());
        $redis->exists($key) && $redis->del($key);
    }
}